package bjtu.student.portrait.util;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.openapitools.jackson.nullable.JsonNullable;

import java.net.URI;
import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@MappedJdbcTypes(JdbcType.VARCHAR)
public class URLTypeHandler extends BaseTypeHandler<JsonNullable<URI>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, JsonNullable<URI> uriJsonNullable, JdbcType jdbcType) throws SQLException {
        preparedStatement.setString(i, uriJsonNullable.get().toString());
    }

    @Override
    public JsonNullable<URI> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        return JsonNullable.of(URI.create(resultSet.getString(s)));
    }

    @Override
    public JsonNullable<URI> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        return JsonNullable.of(URI.create(resultSet.getString(i)));
    }

    @Override
    public JsonNullable<URI> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        return JsonNullable.of(URI.create(callableStatement.getString(i)));
    }
}
